import { _decorator, Component, Node, Vec3, Size, View, view, Collider2D, Contact2DType, director, Director, CCInteger } from 'cc';
import { AudioMgr } from './AudioMgr';
import { enemy } from './enemy';
const { ccclass, property } = _decorator;

@ccclass('bullet')
export class bullet extends Component {

    // 攻击力
    @property(CCInteger)
    hitPower: number = 10;

    speed:number = 5;

    // 可视区域
    viewSize: Size;

    // 子弹发射音源
    shotAudio: string = 'audio/bullet'

    
    start() {
        this.viewSize = view.getVisibleSize()

        this.playShotAudio()


        // 注册碰撞监听
        this.getComponent(Collider2D).on(Contact2DType.BEGIN_CONTACT, this.beginContact)
    }

    update(deltaTime: number) {
        this.shot(deltaTime)
    }


    /**
     * 子弹向上移动
     */
    shot(dt: number) {

        let p = this.node.getPosition()

        // console.log('bullet position', p)

        p.y += 100 * dt * this.speed;

        this.node.setPosition(p)

        if (p.y > this.viewSize.height  + 100) {
            // 销毁
            // console.log('子弹销毁');
            
            this.node.destroy()
        }

    }


    playShotAudio() {
        AudioMgr.inst.playOneShot(this.shotAudio, 0.5)
    }



    /**
     * 
     * 刚体碰撞事件
     * 
     */
    beginContact(self: Collider2D, other: Collider2D) {
        
        console.log('发生碰撞: ', self.tag, '--', other.tag);

        /**
         * 
         * hero 0
         * bullet 1
         * enemy 2
         * 
         */

        // 子弹与敌机相撞, 子弹销毁, 敌机死亡
        if(self.tag == 1 && other.tag == 2 && other.getComponent(enemy).hp > 0) {
            
            
            other.getComponent(enemy).hit(self.getComponent(bullet).hitPower)
            
            director.once(Director.EVENT_AFTER_PHYSICS, () => {
                self.node.destroy()
            })
            
        }
        
    }



}


